<!--
 * Tencent is pleased to support the open source community by making Tars available.
 *
 * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
 *
 * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * https://opensource.org/licenses/BSD-3-Clause
 *
 * Unless required by applicable law or agreed to in writing, software distributed
 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
 * CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
-->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="../css/bootstrap.min.css">
    <link rel="stylesheet" href="../css/bootstrap_table.min.css">
    <link rel="stylesheet" href="../css/style.css">
    <!--[if lt IE 9]>
    <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script src="../js/jquery.min.js"></script>
    <script src="../js/bootstrap.min.js"></script>
    <script src="../js/bootstrap_table.min.js"></script>
    <script src="../js/template.js"></script>
    <script src="../js/common.js"></script>
</head>
<body>
<h4 id="main_title">部署申请</h4>
<form class="form-horizontal" role="form" style="width: 700px;">
    <div class="form-group">
        <div class="col-sm-2"><label for="app-name" class="control-label wp100">应用 <span class="text-danger">*</span></label></div>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="app-name" placeholder="应用名只能包含英文字母" name="application">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-2"><label for="server-name" class="control-label wp100">服务名称 <span class="text-danger">*</span></label></div>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="server-name" placeholder="服务名只能包含英文字母，数字，并以字母开头" name="server_name">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-2"><label class="control-label wp100">服务类型 <span class="text-danger">*</span></label></div>
        <div class="col-sm-10">
            <select name="server_type" id="server-type" class="form-control">
                <option value="tars_cpp">tars_cpp</option>
                <option value="tars_java">tars_java</option>
                <option value="not_tars">not_tars</option>
            </select>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-2"><label class="control-label wp100">模板 <span class="text-danger">*</span></label></div>
        <div class="col-sm-10">
            <select id="id_template" class="form-control" name="template_name"></select>
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-2"><label for="server-name" class="control-label wp100">节点 <span class="text-danger">*</span></label></div>
        <div class="col-sm-10">
            <input type="text" class="form-control" id="node-name" placeholder="节点" name="node_name">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-2"><label class="control-label wp100">Set分组</label></div>
        <div class="col-sm-10">
            <div class="col-sm-3"><label class="checkbox-inline"> <input type="checkbox" id="enable-set" name="enable_set"> 启用Set</label></div>
            <div class="col-sm-3"><input type="text" class="form-control" placeholder="Set名,全英文小写" title="Set名,全英文小写" name="set_name" id="set-name" disabled></div>
            <div class="col-sm-3"><input type="text" class="form-control" placeholder="Set地区,全英文小写" title="Set地区,全英文小写" name="set_area" id="set-area" disabled></div>
            <div class="col-sm-3"><input type="text" class="form-control" placeholder="Set组名,数字或*号" title="Set组名,数字或*号" name="set_group" id="set-group" disabled></div>
        </div>
    </div>
</form>

<form>
    <table class="table table-hover table-bordered" id="obj-table">
        <thead>
            <tr>
                <th>OBJ名称<span class="text-danger">*</span> <span class="blue" data-toggle="tooltip" title="无需加应用和服务，如MTT.HttpProxyServer.HttpProxy2Obj，这里只填HttpProxy2Obj"><i class="glyphicon glyphicon-info-sign"></i></span></th>
                <th>OBJ绑定IP<span class="text-danger">*</span></th>
                <th>端口<span class="text-danger">*</span></th>
                <th>端口类型<span class="text-danger">*</span></th>
                <th>协议<span class="text-danger">*</span></th>
                <th>线程数<span class="text-danger">*</span></th>
                <th>最大连接数<span class="text-danger">*</span></th>
                <th>队列最大长度<span class="text-danger">*</span></th>
                <th>队列超时时间(ms)<span class="text-danger">*</span></th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="text" class="form-control obj-name"></td>
                <td><input type="text" class="form-control bind-ip"></td>
                <td><input type="number" min="0" class="form-control num-control port" placeholder="0~65535"></td>
                <td>
                    <div style="white-space: nowrap">
                        <input type="radio" name="port-type" class="port-type" id="port-type-tcp" value="tcp" checked="true" /><label for="port-type-tcp">TCP</label>
                        <input type="radio" name="port-type" class="port-type" id="port-type-udp" value="udp"/><label for="port-type-udp">UDP</label>
                    </div>
                </td>
                <td>
                    <div style="white-space: nowrap">
                        <input type="radio" name="protocol" class="protocol" id="protocol-tars" value="tars" checked="true" /><label for="protocol-tars">TARS</label>
                        <input type="radio" name="protocol" class="protocol" id="protocol-not-tars" value="not_tars"/><label for="protocol-not-tars">非TARS</label>
                    </div>

                </td>
                <td><input type="number" min="10" style="width: 60px;" class="form-control num-control thread-num" value="5"></td>
                <td><input type="number" min="10" style="width: 100px;" class="form-control num-control max-connections" value="200000"></td>
                <td><input type="number" min="10" style="width: 100px;" class="form-control num-control queuecap" value="10000"></td>
                <td><input type="number" min="10" style="width: 100px;" class="form-control num-control queuetimeout" value="60000"></td>
                <td width="70">
                    <button type="button" class="btn btn-success btn-xs">
                        <span class="glyphicon glyphicon-plus"></span>
                    </button>
                </td>
            </tr>
        </tbody>
    </table>
</form>

<div class="tc">
    <button type="button" class="btn btn-primary" id="btn-submit">提交</button>
</div>


<div id="msg" style="display: none">

</div>



<script>
    $('#enable-set').change(function () {
        if(this.checked){
            $(this).parents('.col-sm-10').find('.form-control').removeAttr('disabled');
        }else{
            $(this).parents('.col-sm-10').find('.form-control').attr('disabled','disabled');
        }
    });

    getTemplateList(function (data) {
        $('#id_template').html(data);
    });

    var $table = $('#obj-table'),tr,lines = 0;
    $table.on('click','.btn-success',function () {
        if(lines<9){
            $tr = $(this).parents('tr').clone();
            $tr.find('.btn-success').attr('class','btn btn-danger btn-xs').find('.glyphicon').attr('class','glyphicon glyphicon-minus');
            $tr.find('.bind-ip').val($.trim($('#node-name').val()));
            $table.find('tbody').append($tr);
            lines++;
        }
    });
    $table.on('click','.btn-danger',function () {
        if(lines>0){
            $(this).parents('tr').remove();
            lines--;
        }
    });
    $table.on('keydown','.obj-name',function(e){
        if((e.keyCode<65 || e.keyCode>90) && (e.keyCode!=8 && e.keyCode!=46)){
            return false;
        }
    });
    $table.on('keydown','.num-control',function (e) {
        if(!(e.keyCode>47 && e.keyCode<59) && !(e.keyCode>95 && e.keyCode<106) && e.keyCode!=8 && e.keyCode!=46){
            return false;
        }
    });
    $('#node-name').keyup(function () {
        $('.bind-ip').val($.trim($(this).val()));
    });
    $('#node-name,#app-name,#server-name').blur(function () {
        var application = $.trim($('#app-name').val()),
            server_name = $.trim($('#server-name').val()),
            node_name   = $.trim($('#node-name').val());
        checkServerExist(application,server_name,node_name);
    });

    $('#btn-submit').click(function () {
        var paramObj = {
            application     :   $.trim($('#app-name').val()),
            server_name     :   $.trim($('#server-name').val()),
            server_type     :   $('#server-type').val(),
            template_name   :   $('#id_template').val(),
            node_name       :   $.trim($('#node-name').val()),
            enable_set      :   $('#enable-set')[0].checked ? true : false,
            set_name        :   $.trim($('#set-name').val()),
            set_area        :   $.trim($('#set-area').val()),
            set_group       :   $.trim($('#set-group').val()),
            adapters        :   []
        };
        closeErrorMsg();
        if(!paramObj.application){
            showErrorMsg($('#main_title'),'应用名不能为空');
            return;
        }
        if(!/^[a-zA-Z]+$/g.test(paramObj.application)){
            showErrorMsg($('#main_title'),'应用名只能包含英文字母');
            return;
        }
        if(!paramObj.server_name){
            showErrorMsg($('#main_title'),'服务名不能为空');
            return;
        }
        if(!/^[a-zA-Z]([a-zA-Z0-9])+$/g.test(paramObj.server_name)){
            showErrorMsg($('#main_title'),'服务名只能包含英文字母，数字，并以字母开头');
            return;
        }
        if(!paramObj.node_name){
            showErrorMsg($('#main_title'),'节点不能为空');
            return;
        }
        if(!/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test(paramObj.node_name)){
            showErrorMsg($('#main_title'),'节点格式不正确，请输入正确的IP地址');
            return;
        }
        if(paramObj.enable_set){
            if(!paramObj.set_name){
                showErrorMsg($('#main_title'),'Set名不能为空');
                return;
            }
            if(!/^[a-z]+$/.test(paramObj.set_name)){
                showErrorMsg($('#main_title'),'Set名只能为英文字母，且必须小写');
                return;
            }
            if(!paramObj.set_area){
                showErrorMsg($('#main_title'),'Set区域不能为空');
                return;
            }
            if(!/^[a-z]+$/.test(paramObj.set_area)){
                showErrorMsg($('#main_title'),'Set区域只能为英文字母，且必须小写');
                return;
            }
            if(!paramObj.set_group){
                showErrorMsg($('#main_title'),'Set组名不能为空');
                return;
            }
            if(!/^(\d+|\*)$/.test(paramObj.set_group)){
                showErrorMsg($('#main_title'),'Set组名只能是数字或*号');
                return;
            }
        }else{
            delete paramObj.set_area;
            delete paramObj.set_name;
            delete paramObj.set_group;
        }
        var $controls = $('#obj-table').find('.form-control'),len = $controls.length,flag=0;
        for(var i=0;i<len;i++){
            if($controls[i].value==''){
                flag=1;
            }
        }
        if(flag==1){
            showErrorMsg($('#main_title'),'所有必填项都必须填写!');
            return;
        }
        $.each($('#obj-table').find('tbody').find('tr'),function () {
            var tmp = {
                obj_name : $.trim($(this).find('.obj-name').val()),
                bind_ip : $.trim($(this).find('.bind-ip').val()),
                port : $.trim($(this).find('.port').val()),
                port_type: $.trim($(this).find('.port-type:checked').val()),
                protocol: $.trim($(this).find('.protocol:checked').val()),
                thread_num : $(this).find('.thread-num').val(),
                max_connections : $(this).find('.max-connections').val(),
                queuecap : $(this).find('.queuecap').val(),
                queuetimeout : $(this).find('.queuetimeout').val()
            };
            paramObj.adapters.push(tmp);
        });
        var param = $.stringify(paramObj);
        checkServerExist(paramObj.application,paramObj.server_name,paramObj.node_name,function(){
            $.ajax('/pages/server/api/deploy_server',{
                contentType:'application/json',
                method:'post',
                data:param,
                dataType:'json',
                success:function (data) {
                    var $msg = $('#msg');
                    if(data.ret_code==200 && data.sub_code!=400){
                        $msg.html('<div class="alert alert-success" role="alert">布署申请提交成功！</div>');
                    }else{
                        $msg.html('<div class="alert alert-danger" role="alert">布署申请提交失败！请联系管理员</div>');
                    }
                    showDialog($msg,'信息提示');
                }
            });
        });
    });


    /**
     * 获取模板名称
     * @param {Function} callback  获取数据后的回调函数
     * @return {String}  html      返回获取到的下拉列表
     */
    function getTemplateList(callback) {
        $.getJSON('/pages/server/api/template_name_list',function (data) {
            if(data.ret_code==200){
                var htmlStr = '';
                $.each(data.data,function (index, n) {
                    htmlStr += '<option value="'+n+'">'+n+'</option>';
                });
                callback(htmlStr);
            }
        });
    }

    /**
     * 检查系统中是否已经存在此服务
     * @param {String}   application  应用名
     * @param {String}   server_name  服务名
     * @param {String}   node_name    节点名
     * @return {String}  html      返回获取到的下拉列表
     */
    function checkServerExist(application,server_name,node_name,callback){
        var paramObj = {
            application     :   application,
            server_name     :   server_name,
            node_name       :   node_name
        };
        for(var k in paramObj){
            if(!paramObj[k]){
                return;
            }
        }
        closeErrorMsg();
        $.getJSON('/pages/server/api/server_exist',paramObj,function (data) {
            if(data.ret_code==200){
                if(data.data){
                    showErrorMsg($('#main_title'),'系统中已存在此服务，请更换应用名，服务名或节点后重试');
                }else{
                    if($.isFunction(callback)){
                        callback();
                    }
                }
            }
        });
    }
</script>
</body>
</html>
